<template>
  <div>
    <el-button type="primary" @click="sseFun">主要按钮</el-button>
    <el-button type="primary" @click="sseStopFun">停止</el-button>
  </div>
</template>
<!-- server: {
    proxy: {
       '/japi': {
            target: 'http://localhost:3001/',
            changeOrigin: true,
            rewrite: path => path.replace(/^\/japi/, ''),
        }, -->
<script>
import { fetchEventSource } from "@microsoft/fetch-event-source";
import { getToken, setToken } from "@/utils/auth";
export default {
  methods: {
    sseFun() {
      this.ctrlAbout = new AbortController();
      debugger
      console.log(this.$store.getters.token,'this.$store.getters.token')
      const url = '/japi'
      const payload = {name:'jiaguoqiang'}
      this.eventSource = fetchEventSource(url, {
        method: "POST",
        signal: this.ctrlAbout.signal,
        headers: {
          "Content-Type": "application/json",
          Accept: "*/*",
          token: getToken() || this.$store.getters.token,
        },
        body: JSON.stringify(payload),
        async onopen(response) {
          if (
            response.ok &&
            response.headers.get("content-type").indexOf("event-stream") > -1
          ) {
            return; // everything's good
          } else {
            // _this.stopAnswer("该问题不在回答范围内");
            console.log('该问题不在回答范围内')
            throw new Error();
          }
        },

        onmessage(event) {
          console.info("event:", event);
          console.info("event.data:", event.data);
        },
        onerror(err) {
          console.log("err:", err);
          console.log("网络错误，请重试");
        },
        onclose(err) {
          console.log("err:", err);
        },
        openWhenHidden: true,
      });
    },
    sseStopFun() {
        this.ctrlAbout.abort()
    }
  },
};
</script>

<style></style>
